package utils

import (
	"errors"
	"github.com/golang-jwt/jwt/v5"
	"time"
)

const key string = "secret"

func GenerateJWT(username string) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"username": username,
		"exp":      time.Now().Add(time.Hour * 72).Unix(), //一个72小时的令牌
	})

	signedToken, err := token.SignedString([]byte(key))
	return "Bearer " + signedToken, err
}

// https://www.topgoer.com/%E5%85%B6%E4%BB%96/JSONWeb%E4%BB%A4%E7%89%8C.html
func ParseJWT(tokenString string) (string, error) {
	if len(tokenString) > 7 && tokenString[:7] == "Bearer " {
		tokenString = tokenString[7:]
	}

	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, errors.New("unexpected Signing Method")
		}
		return []byte(key), nil
	})
	if err != nil {
		return "", err
	}
	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		username, ok := claims["username"].(string)
		if !ok {
			return "", errors.New("username claim is not a string")
		}
		return username, nil
	}

	return "", err
}

func TimeToInt(t time.Time) int {
	year := t.Year()
	month := int(t.Month()) // Month() 返回的是 time.Month 类型，需要转换为 int
	day := t.Day()

	//20241130 etc..
	return year*10000 + month*100 + day
}
